package com.game.modular.gameCore.cultivate.service.impl;

import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.game.modular.gameCore.cultivate.mapper.CoreHeroMapper;
import com.game.modular.gameCore.cultivate.domain.CoreHero;
import com.game.modular.gameCore.cultivate.service.CoreHeroService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 武将基础数据表(CoreHero)表服务实现类
 *
 * @author cxy
 * @since 2024-08-05 16:14:02
 */
@Slf4j
@Service
public class CoreHeroServiceImpl extends ServiceImpl<CoreHeroMapper, CoreHero> implements CoreHeroService {
    Cache<String, Map<Long,CoreHero>> cache = Caffeine.newBuilder().build();
    
    @PostConstruct
    private void init() {
        CoreHero initSelect = CoreHero.builder().build();
        List<CoreHero> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存武将基础数据表数据,数据量为:{}",list.size());
        cache.put(
                "coreHero", 
                list.stream().collect(Collectors.toMap(CoreHero::getId, CoreHero -> CoreHero))
        );
        log.info("武将基础数据表数据缓存完成");
    }

    public List<CoreHero> listCache() {
        Map<Long,CoreHero> values = cache.getIfPresent("coreHero");
        if (Objects.isNull(values)) {
            throw new RuntimeException("武将基础数据表数据为空");
        }
        return new ArrayList<>(values.values());
    }     
    
    public Map<Long,CoreHero> mapCache() {
        Map<Long,CoreHero> values = cache.getIfPresent("coreHero");
        if (Objects.isNull(values)) {
            throw new RuntimeException("武将基础数据表数据为空");
        }
        return values;
    }   
    
    public CoreHero getCache(Long id) {
        Map<Long,CoreHero> values = cache.getIfPresent("coreHero");
        if (Objects.isNull(values)) {
            throw new RuntimeException("武将基础数据表数据为空");
        }
        return values.get(id);
    }
}
